package cn.qzzg.controller;

import cn.qzzg.common.ResultBean;
import cn.qzzg.common.exceptlion.CommonException;
import cn.qzzg.dto.UploadResultDto;
import cn.qzzg.enums.CodeEnum;
import cn.qzzg.pojo.PotTime;
import cn.qzzg.pojo.Review;
import cn.qzzg.pojo.SamplesPersonnel;
import cn.qzzg.pojo.TestTube;
import cn.qzzg.service.PotTimeService;
import cn.qzzg.service.ReviewService;
import cn.qzzg.service.SamplesPersonnelService;
import cn.qzzg.service.TestTubeService;

import  cn.qzzg.dto.TestTubeDto;
import cn.qzzg.vo.ReviewVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.testng.annotations.Test;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/testTube")
public class TestTubeController {
    @Resource
    TestTubeService testTubeService;

    @Resource
    ReviewService reviewService;

    @Resource
    PotTimeService potTimeService;

    @Resource
    SamplesPersonnelService samplesPersonnelService;

    /**
     * 查询所有
     */
    @RequestMapping(value = "/check", method = RequestMethod.GET)
    public ResultBean<?> check(String testTubeId) {
        return ResultBean.success(testTubeService.check(testTubeId));
    }


    /**
     * 查询所有
     */
    @RequestMapping(value = "/queryByTransferBoxId", method = RequestMethod.POST)
    public ResultBean<?> queryByTransferBoxId(@RequestBody String transferBoxId) {
        transferBoxId = transferBoxId.replace("=", "");
        return ResultBean.success(testTubeService.findAllByTransferBoxId(transferBoxId));
    }

    /**
     * 查询所有
     */
    @RequestMapping(value = "/queryAll", method = RequestMethod.POST)
    public ResultBean<?> queryAll(@RequestBody String transferBoxId) {
        transferBoxId = transferBoxId.replace("=", "");
        return ResultBean.success(testTubeService.findAllByTransferBoxId(transferBoxId));
    }

    @RequestMapping(value = "/queryByPotTimeId", method = RequestMethod.POST)
    public ResultBean<?> queryByPotTimeId(@RequestBody String potTimeId) {
        potTimeId = potTimeId.replace("=", "");
        return ResultBean.success(testTubeService.findAllByPotTimeId(potTimeId));
    }

    /**
     * 创建
     *
     * @return true
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ResultBean<?> create(HttpServletRequest request, @RequestBody TestTube testTube) {
        testTube.setReceivingPersonnel(request.getAttribute("name").toString())
                .setTestResults(0);
        return ResultBean.success(testTubeService.saveOne(testTube));
    }

    /**
     * 删除
     *
     * @param myObjet 需要删除的
     * @return true
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ResultBean<?> delete(@RequestBody TestTube myObjet) {
        List<SamplesPersonnel> samplesPersonnelList = samplesPersonnelService.findAllByTestTubeId(myObjet.getTestTubeId());
        List<Integer> list = new ArrayList<>();
        samplesPersonnelList.forEach(samplesPersonnel -> list.add(samplesPersonnel.getSamplesPersonnelId()));
        if (list.size() != 0) {
            samplesPersonnelService.batchRemove(list);
        }
        return ResultBean.success(testTubeService.removeOne(myObjet.getTestTubeId()));
    }

    /**
     * 试管码录入信息（区分复查的试管）
     * @param testTube
     * @return
     */
    @RequestMapping(value = "/entryPotTime", method = RequestMethod.POST)
    public ResultBean<?> entryPotTime(@RequestBody TestTube testTube) {
        //校验参数
        if(StringUtils.isEmpty(testTube.getTestTubeId())||testTube.getPotTimeId()==null||testTube.getPotTimeAddress()==null){
            throw new CommonException(CodeEnum.USER_ERROR_A0400);
        }
        //验证试管有无存在
        TestTube testTube1 = testTubeService.findById(testTube.getTestTubeId());
        if (testTube1 == null) {
            throw new CommonException(CodeEnum.CUSTOM_ERROR_F0102);
        }

        //锅次
        Integer potTimeId = testTube.getPotTimeId();
        Integer newPotTimeId = testTube.getNewPotTimeId();

        boolean isSuccess;

        //是否复查 1复查
        Integer tubeStatus = testTube1.getTubeStatus();
        PotTime potTimeInfo = potTimeService.findPotTimeInfo(potTimeId);

        //验证锅次信息有没存在
        if(potTimeInfo==null){
            throw new CommonException(CodeEnum.CUSTOM_ERROR_F0105);
        }

        //锅次状态
        Integer potStatus = potTimeInfo.getPotStatus();



        if(tubeStatus!=null&& tubeStatus==1){
            //管码为复查,验证锅次是否为复查锅次
            Integer pot_status = potTimeInfo.getPotStatus();
            if(pot_status==null||pot_status!=1){
                throw new CommonException(CodeEnum.CUSTOM_ERROR_F0104);
            }
            //如果复查信息已经录入，则提示已录入
            if (testTube1.getNewPotTimeId() != null && testTube1.getNewPotTimeAddress() != null) {
                throw new CommonException(CodeEnum.CUSTOM_ERROR_F0101);
            }
            //更新复查信息
            testTube1.setNewPotTimeId(potTimeId);
            testTube1.setNewPotTimeAddress(testTube.getPotTimeAddress());
            isSuccess = testTubeService.updateOne(testTube1);
        } else {
            if (testTube1.getPotTimeId() != null && testTube1.getPotTimeAddress() != null) {
                throw new CommonException(CodeEnum.CUSTOM_ERROR_F0101);
            }
            if(potStatus==null||potStatus==0){
                testTube1.setPotTimeId(testTube.getPotTimeId())
                        .setPotTimeAddress(testTube.getPotTimeAddress());
                //无复查
                isSuccess = testTubeService.updateOne(testTube1);
            }else {
                //错误信息（试管需要为正常锅次）
                throw new CommonException(CodeEnum.CUSTOM_ERROR_F0107);
            }
        }
        return ResultBean.success(isSuccess);
    }


    /**
     * 试管码列表--新增判断是否为复查锅次，（新增一个是否复查的字段）
     * @param testTubeDto
     * @return
     */
    @RequestMapping(value = "/queryPage", method = RequestMethod.POST)
    public ResultBean<?> queryPage(@RequestBody TestTubeDto  testTubeDto) {
        return ResultBean.success(testTubeService.findPage(testTubeDto));
    }
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    public ResultBean<?> deleteBatch(@RequestBody List<TestTube> testTubeList) {
        final int[] successNum = {0};
        if(testTubeList==null||testTubeList.size()==0){
            throw new CommonException(CodeEnum.CUSTOM_ERROR_F0108);
        }
        testTubeList.forEach(testTube1 -> {
            TestTube testTube = testTubeService.findById(testTube1.getTestTubeId());
            if(testTube!=null){
                //当前锅次得ID
                Integer potStatus = testTube1.getPotStatus();
                //1、正常锅次结果为已录入的删除
                //2、复查锅结果为复查删除
                Integer testResults = testTube.getTestResults();
                if(potStatus!=null&&potStatus==1){
                    //复查锅次
                    if(testResults!=null && testResults==3){
                        testTube.setNewPotTimeId(null).setNewPotTimeAddress(null);
                        boolean updateInfo = testTubeService.updateInfo(testTube);
                        if(updateInfo){
                            successNum[0] = successNum[0] +1;
                        }
                    }
                }else {
                    //正常锅次
                    if(testResults!=null && testResults==0){
                        testTube.setPotTimeId(null).setPotTimeAddress(null);
                        boolean updateInfo =testTubeService.updateInfo(testTube);
                        if(updateInfo){
                            successNum[0] = successNum[0] +1;
                        }
                    }
                }
            }
        });

        if(successNum[0] ==testTubeList.size()){
            return ResultBean.success();
        }else {
            String errorMsg="操作成功"+ successNum[0] +"条，失败"+(testTubeList.size()- successNum[0]+"条");
            return ResultBean.error("4213",errorMsg);
        }
    }

    /**
     * 上传结果(新增：如果为复查的试管，则将复查类型置为1)
     * @param testTubeList
     * @return
     */
    @RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
    public ResultBean<?> uploadResult(@RequestBody List<TestTube> testTubeList) {
        if(testTubeList==null||testTubeList.size()==0){
            return ResultBean.error(CodeEnum.CUSTOM_ERROR_F0106);
        }
        //遍历结果信息
        for (TestTube testTube:testTubeList){
            Integer potTimeId = testTube.getPotTimeId();
            Integer potTimeAddress = testTube.getPotTimeAddress();

            TestTube tubeInfo=null;
            String testTubeId = testTube.getTestTubeId();

            if(StringUtils.isEmpty(testTubeId)){
                //查询试管信息
                if(potTimeId!=null&& potTimeAddress!=null) {
                    TestTube testTube1 = new TestTube();
                    testTube1.setPotTimeId(potTimeId);
                    testTube1.setPotTimeAddress(potTimeAddress);
                    tubeInfo = testTubeService.findTestTubeInfo(testTube1);
                    if(tubeInfo==null){
                        testTube1 = new TestTube();
                        testTube1.setNewPotTimeId(potTimeId);
                        testTube1.setNewPotTimeAddress(potTimeAddress);
                        tubeInfo = testTubeService.findTestTubeInfo(testTube1);
                    }
                    if(tubeInfo!=null) {
                        testTubeId =tubeInfo.getTestTubeId();
                    }
                }
            }else {
                TestTube tube = new TestTube();
                tube.setTestTubeId(testTubeId);
                tubeInfo = testTubeService.findTestTubeInfo(tube);
            }

            if(!StringUtils.isEmpty(testTubeId)) {
                testTube.setTestTubeId(testTubeId);
                Integer testResults = testTube.getTestResults();
                if(testResults!=null&&testResults==3){
                    //复查的，则将更新复查类型 1:复查
                    testTube.setTubeStatus(1);
                    Review review = new Review();
                    review.setTestTubeId(testTubeId);
                    review.setPotTimeId(potTimeId);
                    Review info = reviewService.findInfo(review);
                    if(info==null){
                        //添加到复查表
                        review.setReviewType(testTube.getReviewType());
                        review.setReagentType(testTube.getReagentType());
                        reviewService.saveOne(review);
                    }
                }

                //修改结果条件：1、正常锅次没复查的   2、复查的锅次

                //potStatus 1：复查锅  0：正常
                Integer tubeStatus = tubeInfo.getTubeStatus();
                if(tubeStatus!=null&&tubeStatus==1){
                    testTubeService.updateOne(testTube);
                }else {
                    if(tubeStatus==null||tubeStatus==0){
                        testTubeService.updateOne(testTube);
                    }
                }
            }
        }
        return ResultBean.success();
    }

    @RequestMapping(value = "/report", method = RequestMethod.POST)
    public ResultBean<?> report(@RequestBody List<TestTube> testTubeList) {
        if(testTubeList==null||testTubeList.size()==0){
            throw new CommonException(CodeEnum.CUSTOM_ERROR_F0109);
        }
        final int[] success = {0};
        testTubeList.forEach(testTube -> {
            TestTube byId = testTubeService.findById(testTube.getTestTubeId());
            if(byId.getTestResults()!=null&&byId.getTestResults()!=0){
                byId.setStatus(1);
                boolean updateOne = testTubeService.updateOne(byId);
                if(updateOne){
                    success[0] = success[0] +1;
                }
            }
        });
//        if (successess[0] == testTubeList.size()) {
            String successMsg="操作成功"+ success[0] +"条，失败"+(testTubeList.size()- success[0]+"条");
            return ResultBean.success(successMsg);
//            return ResultBean.success();
//        } else {
//            String errorMsg="操作成功"+ success[0] +"条，失败"+(testTubeList.size()- success[0]+"条");
//            return ResultBean.error("4213",errorMsg);
//            String errorMsg="操作失败";
//            return ResultBean.error("4213",errorMsg);
//        }
    }
}
